<template>
  <XenPageLayout
    title="编辑请假出差"
    title-align="left"
    navbar-bg-color="#7881de"
    navbar-text-color="#ffffff"
    navbar-icon-color="#ffffff"
    contentStyle="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 0; height: 100vh; display: flex; flex-direction: column;"
  >
    <!-- 表单内容区域 -->
    <view class="form-container">
      <XenDynamicFormCard
        title="编辑请假出差信息"
        :subtitle="`申请单ID: ${leaveId || 'L12345'}`"
        :sections="formSections"
        :modelValue="formData"
        :errors="formErrors"
        :showFooter="false"
        @update:modelValue="handleFormDataChange"
        @fieldBlur="handleFieldBlur"
        @pickerChange="handlePickerChange"
        @datetimeChange="handleDateTimeChange"
        @imageUpload="handleImageUpload"
        @imageSuccess="handleImageSuccess"
        @imageFail="handleImageFail"
        @imageDelete="handleImageDelete"
        @fileUpload="handleFileUpload"
        @fileSuccess="handleFileSuccess"
        @fileFail="handleFileFail"
        @fileDelete="handleFileDelete"
        @departmentPickerChange="handleDepartmentPickerChange"
        @departmentPickerOpen="handleDepartmentPickerOpen"
        @departmentPickerClose="handleDepartmentPickerClose"
        @autoCompleteChange="handleAutoCompleteChange"
        @autoCompleteSearch="handleAutoCompleteSearch"
      />
    </view>

    <!-- 固定底部操作按钮 -->
    <XenFormActions
      :actions="formActions"
      :hidden="isDepartmentPickerOpen"
      @action="handleFormAction"
    />
  </XenPageLayout>
</template>

<script setup lang="ts">
import { onMounted, ref, computed, watch } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import XenPageLayout from "@/layouts/XenPageLayout.vue";
import XenDynamicFormCard from "@/components/XenDynamicFormCard.vue";
import XenFormActions from "@/components/XenFormActions.vue";
import { getFormSectionsByPageType } from "./form-config";
import { useLeaveInfo } from "./composables/useInfo";
// 导入统一事件系统
import { ResignInfoEvents } from "@/utils/eventBus";
// 导入API和接口类型
import SysDailyLeaveRequestBillApi from "./api/index";
import type { ISysDailyLeaveRequestBillVm } from "./api/interface";
import commonApi from "@/api/common";
import type { ICompanyItem } from "@/type/common";

// 获取路由参数
const leaveId = ref<string>("");

// 创建API实例
const api = SysDailyLeaveRequestBillApi();
const commonApiInstance = commonApi();

// 审核权限标识
const isMyApprove = ref<boolean>(false);

// 部门选择器打开状态
const isDepartmentPickerOpen = ref<boolean>(false);

// 公司和部门数据
const companyList = ref<ICompanyItem[]>([]);
const departmentList = ref<any[]>([]);

// 获取编辑页面的表单分组
const formSections = getFormSectionsByPageType("edit");

// 表单操作按钮配置
const formActions = computed(() => [
  {
    key: "save",
    label: isMyApprove.value ? "取消" : "保存",
    type: "success" as const,
  },
  {
    key: "submit",
    label: "提交",
    type: "primary" as const,
  },
]);

// 使用请假出差申请信息 Composable
const {
  formData,
  formErrors,
  pickerValues,
  validateField,
  handlePickerChange,
  handleDateTimeChange,
  initializeOptions,
  loadLeaveDetail,
  search,
  originalData,
  convertFormDataToApiFormatForEdit,
  calculateDays,
} = useLeaveInfo();

// 根据公司ID获取公司名称
const getCompanyNameById = (orgId: string | null): string => {
  if (!orgId || !companyList.value.length) return "";

  const company = companyList.value.find((item) => item.Value === orgId);
  return company ? company.Text : "";
};

// 根据部门ID获取部门名称（递归查找，支持多级部门）
const getDepartmentNameById = (groupId: string | null): string => {
  if (!groupId || !departmentList.value.length) return "";

  // 递归查找部门
  const findDepartmentById = (departments: any[], id: string): any => {
    for (const dept of departments) {
      if (dept.ID === id || dept.Value === id) {
        return dept;
      }
      if (dept.Children && dept.Children.length > 0) {
        const found = findDepartmentById(dept.Children, id);
        if (found) return found;
      }
    }
    return null;
  };

  const department = findDepartmentById(departmentList.value, groupId);
  return department
    ? department.Text || department.GroupName || department.Name
    : "";
};

// 加载公司列表
const loadCompanyList = async () => {
  const response = await commonApiInstance.GetUserCompanies();
  if (response && Array.isArray(response)) {
    companyList.value = response;
  }
};

// 加载部门列表
const loadDepartmentList = async () => {
  const response = await commonApiInstance.GetParentsTree();
  if (response && Array.isArray(response)) {
    departmentList.value = response;
  }
};

// 处理公司信息显示
const processCompanyInfo = () => {
  if (originalData.value && originalData.value.OrgId) {
    const companyName = getCompanyNameById(originalData.value.OrgId);
    if (companyName) {
      formData.orgName = companyName;
    }
  }
};

// 处理部门信息显示
const processDepartmentInfo = () => {
  if (originalData.value && originalData.value.GroupId) {
    const departmentName = getDepartmentNameById(originalData.value.GroupId);
    if (departmentName) {
      formData.groupName = departmentName;
    }
  }
};

// 表单数据变化处理
const handleFormDataChange = (newData: Record<string, any>) => {
  Object.assign(formData, newData);
};

// 字段失焦处理
const handleFieldBlur = (fieldKey: string) => {
  validateField(fieldKey);
};

// 部门选择器变化处理
const handleDepartmentPickerChange = (
  fieldKey: string,
  value: string,
  _item: any,
) => {
  // XenDynamicFormCard组件会同时触发 @update:model-value 和 @change 事件
  // @update:model-value 已经通过 handleFormDataChange 设置了 formData[fieldKey] = value (部门ID)
  // 这里我们只需要保存部门ID到pickerValues中，用于提交到后端

  // 确保formData中存储的是部门ID（用于组件正确显示选中状态）
  formData[fieldKey] = value;

  // 同时保存到pickerValues中（用于提交到后端）
  pickerValues[fieldKey] = value;

  // 触发验证
  validateField(fieldKey);
};

// 部门选择器弹框打开处理
const handleDepartmentPickerOpen = () => {
  isDepartmentPickerOpen.value = true;
};

// 部门选择器弹框关闭处理
const handleDepartmentPickerClose = () => {
  isDepartmentPickerOpen.value = false;
};

// 自动补全变化处理
const handleAutoCompleteChange = (
  fieldKey: string,
  _value: string,
  option: any,
) => {
  // 对于自动补全，formData中存储显示文本，pickerValues中存储实际值
  if (option) {
    formData[fieldKey] = option.text;
    pickerValues[fieldKey] = option.value;

    // 如果是员工选择，自动填入员工工号、姓名、公司和部门信息
    if (fieldKey === "personId" && option.subtitle) {
      // 从subtitle中提取工号，格式为 "工号: 12345 | 部门名称"
      const staffNoMatch = option.subtitle.match(/工号:\s*(\S+)/);
      if (staffNoMatch) {
        formData.staffNo = staffNoMatch[1];
      }
      // 员工姓名就是选中的文本
      formData.name = option.text;

      // 如果有扩展数据，自动填入公司和部门信息
      if (option.extData) {
        // 更新表单数据
        formData.orgName = option.extData.orgName || "";
        formData.groupName = option.extData.groupName || "";

        // 更新选择器值
        pickerValues.orgId = option.extData.orgId || "";
        pickerValues.groupId = option.extData.groupId || "";

        // 同步到表单数据中的隐藏字段
        formData.orgId = option.extData.orgId || "";
        formData.groupId = option.extData.groupId || "";
      }
    }
  } else {
    formData[fieldKey] = "";
    pickerValues[fieldKey] = "";

    // 如果清空员工选择，也清空员工工号、姓名、公司和部门信息
    if (fieldKey === "personId") {
      formData.staffNo = "";
      formData.name = "";
      formData.orgName = "";
      formData.groupName = "";
      formData.orgId = "";
      formData.groupId = "";
      pickerValues.orgId = "";
      pickerValues.groupId = "";
    }
  }

  // 触发验证
  validateField(fieldKey);
};

// 自动补全搜索处理
const handleAutoCompleteSearch = async (fieldKey: string, query: string) => {
  // 搜索逻辑已经在组件内部通过searchApi处理
  console.log("搜索:", fieldKey, query);
};

// 监听开始时间和结束时间变化，自动计算天数
watch(
  [() => formData.startTime, () => formData.endTime],
  ([startTime, endTime]) => {
    if (startTime && endTime) {
      formData.days = calculateDays(startTime, endTime);
    } else {
      formData.days = "";
    }
  },
);

// 获取路由参数
onLoad((options) => {
  if (options?.id) {
    leaveId.value = options.id;
  } else {
    uni.showToast({
      title: "缺少ID参数",
      icon: "none",
    });
  }
});

// 页面加载时获取数据
onMounted(async () => {
  // 并行初始化选项数据、公司列表和部门列表
  await Promise.all([
    initializeOptions(),
    loadCompanyList(),
    loadDepartmentList(),
  ]);

  // 加载请假出差申请详情
  if (leaveId.value) {
    const result = await loadLeaveDetail(leaveId.value);
    if (!result.success) {
      uni.showToast({
        title: "加载数据失败",
        icon: "none",
      });
    } else {
      // 保存审核权限标识
      isMyApprove.value = result.isMyApprove || false;

      // 处理公司和部门信息显示
      processCompanyInfo();
      processDepartmentInfo();
    }
  }
});

// 图片上传处理
const handleImageUpload = async (field: any, event: any) => {
  // 图片上传逻辑
  console.log("图片上传:", field.key, event);
};

const handleImageSuccess = (_field: any, _event: any) => {
  // 图片上传成功处理
};

const handleImageFail = (_field: any, _event: any) => {
  // 图片上传失败处理
};

const handleImageDelete = (field: any, event: any) => {
  // 图片删除逻辑
  console.log("图片删除:", field.key, event);
};

// 文件上传处理
const handleFileUpload = async (_field: any, _event: any) => {
  // 文件上传逻辑
};

const handleFileSuccess = (_field: any, _event: any) => {
  // 文件上传成功处理
};

const handleFileFail = (_field: any, _event: any) => {
  // 文件上传失败处理
};

const handleFileDelete = (_field: any, _event: any) => {
  // 文件删除处理
};

// 通用的审核处理方法
const performAudit = async (actionName: string) => {
  try {
    const loadingTitle = actionName === "同意" ? "提交中..." : "取消中...";
    uni.showLoading({ title: loadingTitle });

    // 确保有原始数据（包含BillStatus和WorkflowStatus）
    if (!originalData.value) {
      uni.hideLoading();
      uni.showToast({
        title: "缺少原始数据，请重新加载页面",
        icon: "none",
      });
      return;
    }

    // 构造approve接口请求参数
    // 1. 先使用用户编辑的表单数据构造基础Entity
    const editData = convertFormDataToApiFormatForEdit();

    // 2. 然后覆盖状态字段，使用原始数据中的状态信息
    editData.Entity.BillStatus = originalData.value.BillStatus;
    editData.Entity.WorkflowStatus = originalData.value.WorkflowStatus;

    const requestData: ISysDailyLeaveRequestBillVm = {
      ActionName: actionName,
      Entity: editData.Entity, // 使用用户编辑的数据 + 原始状态字段
      IsMyApprove: isMyApprove.value, // 使用从详情接口获取的审核权限标识
    };

    // 调用approve接口
    const result = await api.approve(requestData);

    uni.hideLoading();

    if (result) {
      // 重新调用search接口获取最新的完整列表数据
      try {
        const searchResponse = await search({});
        if (searchResponse && searchResponse.length > 0) {
          // 发送完整列表数据更新事件
          ResignInfoEvents.emit("refresh", {
            id: result.ID || "",
            data: searchResponse,
            customAction: actionName === "同意" ? "approve" : "reject",
          });
        }
      } catch (error) {
        // 如果获取失败，仍然发送简单的刷新事件作为备用方案
        ResignInfoEvents.emit("refresh", {
          id: result.ID || "",
          customAction: actionName === "同意" ? "approve" : "reject",
        });
      }

      const successTitle = actionName === "同意" ? "提交成功" : "取消成功";
      uni.showToast({
        title: successTitle,
        icon: "success",
        success: () => {
          setTimeout(() => {
            uni.navigateBack();
          }, 1000);
        },
      });
    } else {
      const errorTitle =
        actionName === "同意" ? "提交失败，请重试" : "取消失败，请重试";
      uni.showToast({
        title: errorTitle,
        icon: "none",
      });
    }
  } catch (error) {
    uni.hideLoading();
    const errorTitle =
      actionName === "同意" ? "提交失败，请重试" : "取消失败，请重试";
    console.error(`${actionName}失败:`, error);
    uni.showToast({
      title: errorTitle,
      icon: "error",
    });
  }
};

// 编辑保存方法
const performEdit = async (isSubmit: boolean = false) => {
  try {
    const loadingTitle = isSubmit ? "提交中..." : "保存中...";
    uni.showLoading({ title: loadingTitle });

    // 确保有原始数据
    if (!originalData.value) {
      uni.hideLoading();
      uni.showToast({
        title: "缺少原始数据，请重新加载页面",
        icon: "none",
      });
      return;
    }

    // 构造Edit接口请求参数
    const editData = convertFormDataToApiFormatForEdit();

    // 确保使用原始数据中的状态字段
    editData.Entity.BillStatus = originalData.value.BillStatus;
    editData.IsMyApprove = isMyApprove.value; // 使用从详情接口获取的IsMyApprove值

    // 根据操作类型设置WorkflowStatus
    if (isSubmit) {
      // 提交操作：设置WorkflowStatus为"提交中"
      editData.Entity.WorkflowStatus = "提交中";
    } else {
      // 保存操作：使用原始的WorkflowStatus
      editData.Entity.WorkflowStatus = originalData.value.WorkflowStatus;
    }

    // 调用Edit接口
    const result = await api.edit(editData);

    uni.hideLoading();

    if (result) {
      // 重新调用search接口获取最新的完整列表数据
      try {
        const searchResponse = await search({});
        if (searchResponse && searchResponse.length > 0) {
          // 发送完整列表数据更新事件
          ResignInfoEvents.emit("refresh", {
            id: result.ID || "",
            data: searchResponse,
            customAction: isSubmit ? "submit" : "save",
          });
        }
      } catch (error) {
        // 如果获取失败，仍然发送简单的刷新事件作为备用方案
        ResignInfoEvents.emit("refresh", {
          id: result.ID || "",
          customAction: isSubmit ? "submit" : "save",
        });
      }

      const successTitle = isSubmit ? "提交成功" : "保存成功";
      uni.showToast({
        title: successTitle,
        icon: "success",
        success: () => {
          if (isSubmit) {
            // 提交成功后跳转页面
            setTimeout(() => {
              uni.navigateBack();
            }, 1000);
          }
          // 保存成功后不跳转页面
        },
      });
    } else {
      const errorTitle = isSubmit ? "提交失败，请重试" : "保存失败，请重试";
      uni.showToast({
        title: errorTitle,
        icon: "none",
      });
    }
  } catch (error) {
    uni.hideLoading();
    const errorTitle = isSubmit ? "提交失败，请重试" : "保存失败，请重试";
    console.error(`${isSubmit ? "提交" : "保存"}失败:`, error);
    uni.showToast({
      title: errorTitle,
      icon: "error",
    });
  }
};

// 同意操作
const handleApprove = async () => {
  await performAudit("同意");
};

// 拒绝操作
const handleReject = async () => {
  await performAudit("拒绝");
};

// 表单操作处理
const handleFormAction = (action: any) => {
  switch (action.key) {
    case "save":
      handleSaveAction();
      break;
    case "submit":
      handleSubmitAction();
      break;
    default:
      console.log("未知操作:", action.key);
  }
};

// 保存按钮处理方法
const handleSaveAction = async () => {
  if (isMyApprove.value) {
    // 如果IsMyApprove为true，调用拒绝接口
    await handleReject();
  } else {
    // 如果IsMyApprove为false，调用编辑保存接口
    await performEdit(false);
  }
};

// 提交按钮处理方法
const handleSubmitAction = async () => {
  if (isMyApprove.value) {
    // 如果IsMyApprove为true，调用同意接口
    await handleApprove();
  } else {
    // 如果IsMyApprove为false，调用编辑提交接口（WorkflowStatus设为"提交中"）
    await performEdit(true);
  }
};
</script>

<style lang="scss" scoped>
.form-container {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
  // 为固定底部按钮预留空间：按钮44px + 上下padding32px + 边框1px + 缓冲15px + 安全区域
  padding-bottom: calc(92px + constant(safe-area-inset-bottom));
  padding-bottom: calc(92px + env(safe-area-inset-bottom));
}
</style>
